package ru.irenproject.lib;

/*
 Copyright (c) 2009, Orbitz World Wide
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 * Neither the name of the Orbitz World Wide nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 Modified by Sergey Ostanin. The original file is
   https://protobuf-java-format.googlecode.com/svn/tags/1.2/src/main/java/com/googlecode/protobuf/format/SmileFormat.java
*/

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;

import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;

/**
 * The implementation largely follows google/protobuf/text_format.cc.
 * <p>
 * (c) 2011 Neustar, Inc. All Rights Reserved.
 *
 * @author jeffrey.damick@neustar.biz Jeffrey Damick Based on the original code
 *         by:
 * @author eliran.bivas@gmail.com Eliran Bivas
 * @author aantonov@orbitz.com Alex Antonov
 *         <p/>
 * @author wenboz@google.com Wenbo Zhu
 * @author kenton@google.com Kenton Varda
 */
public final class ProtobufToJsonConverter {
  private static final JsonFactory fJsonFactory = new JsonFactory();

  /**
   * Outputs JSON representation of the Protocol Message supplied into the
   * parameter output. (This representation is the new version of the classic
   * "ProtocolPrinter" output from the original Protocol Buffer system)
   */
  public static void print(Message message, OutputStream output, ProtobufToJsonHelper helper) throws IOException {
    JsonGenerator generator = createGenerator(output);
    print(message, generator, helper);
    generator.close();
  }

  /**
   * Outputs JSON representation of the Protocol Message supplied into the
   * parameter output. (This representation is the new version of the classic
   * "ProtocolPrinter" output from the original Protocol Buffer system)
   */
  public static void print(Message message, JsonGenerator generator, ProtobufToJsonHelper helper) throws IOException {
    generator.writeStartObject();
    printMessage(message, generator, helper);
    generator.writeEndObject();
    generator.flush();
  }

  private static JsonGenerator createGenerator(OutputStream output) throws IOException {
    return fJsonFactory.createJsonGenerator(output);
  }

  private static void printMessage(Message message, JsonGenerator generator, ProtobufToJsonHelper helper) throws IOException {
    for (Map.Entry<String, String> e : helper.getExtraFields(message).entrySet()) {
      generator.writeFieldName(e.getKey());
      generator.writeString(e.getValue());
    }

    for (FieldDescriptor fd : message.getDescriptorForType().getFields()) {
      if (fd.isRepeated() || message.hasField(fd)) {
        printField(fd, message.getField(fd), generator, helper);
      }
    }
  }

  private static void printField(FieldDescriptor field, Object value, JsonGenerator generator, ProtobufToJsonHelper helper) throws IOException {
    generator.writeFieldName(camelCase(field.getName()));

    if (field.isRepeated()) {
      // Repeated field. Print each element.
      generator.writeStartArray();
      for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
        printFieldValue(field, iter.next(), generator, helper);
      }
      generator.writeEndArray();
    } else {
      printFieldValue(field, value, generator, helper);
    }
  }

  private static void printFieldValue(FieldDescriptor field, Object value, JsonGenerator generator, ProtobufToJsonHelper helper) throws IOException {
    switch (field.getType()) {
      case INT32:
      case SINT32:
      case SFIXED32:
      case UINT32:
      case FIXED32:
        generator.writeNumber((Integer) value);
        break;

      case INT64:
      case SINT64:
      case SFIXED64:
      case UINT64:
      case FIXED64:
        generator.writeNumber((Long) value);
        break;

      case FLOAT:
        generator.writeNumber((Float) value);
        break;

      case DOUBLE:
        generator.writeNumber((Double) value);
        break;

      case BOOL:
        generator.writeBoolean((Boolean) value);
        break;

      case STRING:
        generator.writeString((String) value);
        break;

      case BYTES: {
        byte[] ba = ((ByteString) value).toByteArray();
        if (helper.isBase64Field(field)) {
          generator.writeBinary(ba);
        } else {
          generator.writeString(Hex.encodeHexString(ba));
        }
        break;
      }

      case ENUM: {
        generator.writeString(((EnumValueDescriptor) value).getName());
        break;
      }

      case MESSAGE:
      case GROUP:
        generator.writeStartObject();
        printMessage((Message) value, generator, helper);
        generator.writeEndObject();
        break;
    }
  }

  /*
   * from https://code.google.com/p/cap-library/source/browse/java/com/google/publicalerts/cap/CapUtil.java?r=7321fbb77c6c241db7247cff8574745aed8999da
   *
   * Copyright (C) 2011 Google Inc.
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not
   * use this file except in compliance with the License. You may obtain a copy of
   * the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   * License for the specific language governing permissions and limitations under
   * the License.
  */
  private static String camelCase(String s) {
    String[] parts = s.split("_");
    StringBuilder sb = new StringBuilder(parts[0].toLowerCase());
    for (int i = 1; i < parts.length; i++) {
      String part = parts[i];
      sb.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
    }
    return sb.toString();
  }

  private ProtobufToJsonConverter() {}
}
